#include "webcontainer.h"
#include "webpage.h"
#include "webview.h"
#include <QScreen>
#include <QVBoxLayout>
#include <QWebEngineFullScreenRequest>
#include <QWebEngineView>

WebContainer::WebContainer(WebPage* page, QWidget* parent)
    : WebContainer(WebView::CreateWindowFunction(), page, parent)
{
}

WebContainer::WebContainer(WebView::CreateWindowFunction cwf, WebPage* page, QWidget* parent)
    : QFrame(parent)
{
    QVBoxLayout* vl = new QVBoxLayout(this);
    vl->setContentsMargins(0, 0, 0, 0);

    web_view_ = new WebView(cwf, this);
    web_view_->setContextMenuPolicy(Qt::NoContextMenu);
    web_view_->setPage(page);
    vl->addWidget(web_view_, 1);

    setFocusProxy(web_view_);

    connect(page, &QWebEnginePage::fullScreenRequested, this,
            [this](QWebEngineFullScreenRequest request) {
                request.accept();
                if (request.toggleOn()) {
                    // 保存顶层窗口状态
                    window_state_ = window()->windowState();
                    // 隐藏顶层窗口
                    window()->showFullScreen();
                    // 全屏WebView
                    web_view_->setParent(window());
                    web_view_->move(0, 0);
                    if (QScreen* s = window()->screen()) {
                        web_view_->resize(s->size());
                    }
                    web_view_->showFullScreen();
                    web_view_->raise();
                    web_view_->setFocus();
                } else {
                    // 恢复WebView
                    web_view_->setParent(this);
                    QVBoxLayout* main_layout = qobject_cast<QVBoxLayout*>(layout());
                    Q_ASSERT(main_layout);
                    main_layout->addWidget(web_view_, 1);
                    web_view_->showNormal();
                    // 恢复顶层窗口状态
                    if (window_state_ & Qt::WindowMaximized) {
                        window()->showMaximized();
                        window()->activateWindow();
                    } else {
                        window()->showNormal();
                        window()->activateWindow();
                    }
                    window()->raise();
                }
            });
}

void WebContainer::exitFullScreen()
{
    if (QWebEnginePage* page = web_view_->page()) {
        page->triggerAction(QWebEnginePage::ExitFullScreen, true);
    }
}
